<template>
  <el-dialog v-model="visible" :title="'AI 智能推荐'" width="600px" @close="handleClose">
    <el-form>
      <el-form-item label="需求描述">
        <el-input
          type="textarea"
          v-model="userRequirement"
          placeholder="请描述您的需求，例如'适合夏季户外运动的男士T恤，价格在200元以内'"
          :rows="4"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleGenerate">生成推荐</el-button>
      </span>
    </template>

    <el-divider v-if="recommendedProducts.length > 0" />

    <el-table v-if="recommendedProducts.length > 0" :data="recommendedProducts" style="width: 100%">
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">
          ￥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <div class="button-group">
            <el-button size="small" class="action-btn" type="primary" @click="addToCart(scope.row.id)">加入购物车</el-button>
            <el-button size="small" class="action-btn" type="success" @click="buyNow(scope.row.id)">购买</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="recommendedProducts.length > 0" style="margin-top: 15px; text-align: right;">
      <el-button type="danger" plain @click="addAllToCart">一键加入全部到购物车</el-button>
      <el-button type="success" plain @click="buyAll">一键全部购买</el-button>
    </div>

    <!-- Order confirmation for单个商品 -->
    <OrderConfirmationDialog
      v-if="currentProduct"
      v-model:visible="orderDialogVisible"
      :product="currentProduct"
      :quantity="1"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useCartStore } from '../stores/cart';
import { useUserStore } from '../stores/user';
import apiClient from '../axios/axios';
import OrderConfirmationDialog from './OrderConfirmationDialog.vue';

interface Product {
  id: number;
  name: string;
  description: string;
  price: number;
  categoryId: string;
  quantity: number;
  imageUrl: string;
}

// Props
const props = defineProps<{
  modelValue: boolean;
  products: Product[];
}>();

const emit = defineEmits(['update:modelValue']);

const cartStore = useCartStore();
const userStore = useUserStore();

const visible = ref(props.modelValue);
watch(() => props.modelValue, val => { visible.value = val; });
watch(visible, val => { emit('update:modelValue', val); });

const userRequirement = ref('');
const loading = ref(false);
const recommendedProducts = ref<Product[]>([]);
const orderDialogVisible = ref(false);
const currentProduct = ref<Product | null>(null);

// === OpenAI Config placeholders ===
const OPENAI_BASE_URL = 'https://x666.me/v1/chat/completions'; // <- 在此填写 OpenAI Base URL，例如 https://api.openai.com/v1/chat/completions
const OPENAI_API_KEY = 'sk-qVxX369CIGKKJsgPEjpYQrJ7msTA61OkKTncustm7DaaziHj';  // <- 在此填写 OpenAI API Key
const OPENAI_MODEL = 'gemini-2.5-pro-preview-06-05'; // <- 在此填写模型名称
// ==================================

const systemPrompt = `你是一位电商导购助手。我会给你一段用户需求描述和一个商品列表（JSON 数组）。\n` +
  `请按照以下要求回复：\n` +
  `1. 仅输出 JSON 格式，不要输出其他任何内容。\n` +
  `2. JSON 中必须包含字段 productIds，它是一个数组，数组元素为你推荐的商品 id（number 类型）。\n` +
  `3. 请选择 1~6 个最适合用户需求的商品，按照相关性从高到低排序。`;

const buildUserPrompt = () => {
  const productsJson = JSON.stringify(props.products);
  return `用户需求: ${userRequirement.value}\n商品列表: ${productsJson}`;
};

const handleGenerate = async () => {
  if (!userRequirement.value.trim()) {
    ElMessage.warning('请先输入您的需求描述');
    return;
  }

  if (!OPENAI_BASE_URL || !OPENAI_API_KEY) {
    ElMessage.error('请先配置 OpenAI BASE_URL 与 API_KEY');
    return;
  }

  loading.value = true;
  try {
    const response = await fetch(OPENAI_BASE_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${OPENAI_API_KEY}`
      },
      body: JSON.stringify({
        model: OPENAI_MODEL,
        messages: [
          { role: 'system', content: systemPrompt },
          { role: 'user', content: buildUserPrompt() }
        ]
      })
    });

    if (!response.ok) {
      throw new Error(`OpenAI 请求失败: ${response.statusText}`);
    }

    const data = await response.json();
    const content = (data.choices?.[0]?.message?.content || '').trim();

    // 清理可能的 Markdown 代码块标记 ```json ... ```
    const cleanedContent = content
      .replace(/^```[a-zA-Z]*\s*/i, '')  // 去掉开头 ``` 或 ```json
      .replace(/```$/, '')                // 去掉结尾 ```
      .trim();

    let result;
    try {
      result = JSON.parse(cleanedContent);
    } catch (error) {
      console.error('JSON 解析失败', error);
      console.error('原始内容:', content);
      ElMessage.error('解析大模型返回结果失败，请稍后重试');
      return;
    }

    const ids: number[] = result.productIds || [];
    recommendedProducts.value = props.products.filter(p => ids.includes(p.id));
    if (recommendedProducts.value.length === 0) {
      ElMessage.info('未找到符合条件的商品');
    }
  } catch (error: any) {
    console.error(error);
    ElMessage.error(error.message || '调用大模型失败');
  } finally {
    loading.value = false;
  }
};

const addToCart = (productId: number) => {
  cartStore.addItem(productId, 1);
  ElMessage.success('已加入购物车');
};

const buyNow = (productId: number) => {
  const prod = props.products.find(p => p.id === productId) || null;
  if (!prod) return;
  currentProduct.value = prod;
  orderDialogVisible.value = true;
};

const addAllToCart = () => {
  recommendedProducts.value.forEach(p => cartStore.addItem(p.id, 1));
  ElMessage.success('已将所有推荐商品加入购物车');
};

const buyAll = async () => {
  if (recommendedProducts.value.length === 0) {
    ElMessage.info('暂无可购买的推荐商品');
    return;
  }

  const user = userStore.user;
  if (!user) {
    ElMessage.error('请先登录');
    return;
  }

  try {
    // 获取用户地址
    const addrRes = await apiClient.get<any[]>(`/address/user/${user.id}`);
    const addresses = addrRes.data;
    if (!addresses.length) {
      ElMessage.warning('请先添加收货地址');
      return;
    }
    const addressId = addresses[0].id;

    const orderPromises = recommendedProducts.value.map((p, idx) => {
      const isFirst = idx === 0;
      const shippingFee = isFirst ? 10 : 0; // 示例运费
      const discountAmount = 0; // 示例折扣
      const payload = {
        customerId: user.id,
        productId: p.id,
        addressId,
        subtotalAmount: p.price,
        shippingFee,
        discountAmount,
        totalAmount: p.price + shippingFee - discountAmount,
      };
      return apiClient.post('/orders', payload);
    });

    await Promise.all(orderPromises);
    ElMessage.success(`成功创建 ${recommendedProducts.value.length} 个订单！`);
    visible.value = false;
  } catch (e) {
    console.error('批量下单失败', e);
    ElMessage.error('批量下单失败，请稍后重试');
  }
};

const handleClose = () => {
  userRequirement.value = '';
  recommendedProducts.value = [];
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
.button-group {
  display: flex;
  gap: 8px;
}
.action-btn {
  width: 80px;
}
</style> 